package pers.qianyu.comment.service;


import com.baomidou.mybatisplus.core.conditions.query.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import pers.qianyu.comment.converter.*;
import pers.qianyu.comment.dao.*;
import pers.qianyu.comment.pojo.dto.*;
import pers.qianyu.comment.pojo.entity.*;
import pers.qianyu.comment.pojo.vo.*;

import java.time.*;
import java.util.*;
import java.util.stream.*;

@Service
public class CommentService {
    @Autowired
    private CommentDao commentDao;
    @Autowired
    private CommentConverter commentConverter;

    /**
     * 根据评论对象 id 获取下面所有评论
     *
     * @param topicId 表示评论对象id
     * @return 评论对象列表
     */
    public List<CommentVO> findCommentsByTopicId(Long topicId) {
        QueryWrapper<CommentPO> wrapper = new QueryWrapper<>();
        wrapper.eq("topic_id", topicId);
        List<CommentPO> commentPOList = commentDao.selectList(wrapper);
        List<CommentVO> commentVOList = commentPOList.stream()
                .map(commentConverter::convertToVO)
                .collect(Collectors.toList());
        List<CommentVO> result = new ArrayList<>();
        HashMap<Long, CommentVO> map = new HashMap<>();
        for (CommentVO commentVO : commentVOList) {
            if (Objects.isNull(commentVO.getParentId())) {
                result.add(commentVO);
            }
            map.put(commentVO.getId(), commentVO);
        }
        for (CommentVO commentVO : commentVOList) {
            if (Objects.nonNull(commentVO.getParentId())) {
                CommentVO parent = map.get(commentVO.getParentId());
                if (Objects.nonNull(parent)) {
                    List<CommentVO> children = parent.getChildren();
                    children.add(commentVO);
                }
            }
        }
        return result;
    }

    /**
     * 插入一条评论
     *
     * @param commentDTO 评论传输对象
     */
    public void insertComment(CommentDTO commentDTO) {
        CommentPO commentPO = commentConverter.convertToPO(commentDTO);
        commentPO.setCreateTime(LocalDateTime.now());
        commentPO.setUpdateTime(commentPO.getCreateTime());
        commentDao.insert(commentPO);
    }

    /**
     * 根据评论 id 查找评论
     *
     * @param id 评论 id
     * @return 查找结果
     */
    public CommentVO findById(Long id) {
        CommentPO commentPO = commentDao.selectById(id);
        CommentVO commentVO = commentConverter.convertToVO(commentPO);
        return commentVO;
    }

}
